<template>
	<view class="content">
		<u-navbar back-text="" :leftText="user1.nick_name" :fixed="true" titleStyle ="font-size:36rpx" slot="left" :autoBack="true" safeAreaInsetTop placeholder>
			<view slot="right" class="leftText dis-row">
				<view class="search" v-if="userFrom.from==loginHxName" @click="callTel()">
					<image src="http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/user-avatar1.svg"></image>打电话 						 
				</view>
			</view>
		</u-navbar>
		<view class="msgTop" id="msgTop" v-if="userFrom.to==loginHxName">
		<!-- <view class="msgTop" id="msgTop" v-if="userFrom.to==loginHxName"> -->
			<view @click="callTel()"><image src="http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/user-avatar1.svg"></image><text>打电话</text></view>
			<view @click="addCard()"><image src="http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/user-avatar.svg"></image><text>加入名片</text></view>
			<view @click="getPhone()"><image src="http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/user-avatar2.svg"></image><text>获取号码</text></view>
			<view @click="checkperson()"><image src="http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/user-avatar3.svg"></image><text>评价</text></view>
		</view>

		<view class="h-20"></view>
		<scroll-view scroll-y="true" :class="userFrom.to==loginHxName?'scroll2':'scroll1'" @scrolltoupper="scrollTopSS()" :scroll-into-view="scrollInto">
		<!-- <view style="height: 140rpx;" v-if="userFrom.to==loginHxName"></view> -->
		<block v-for="(item,index) in historiMessages">
		<view class="job" id="message-scroll" 
			v-if="(item.type=='custom' || item.contentsType=='CUSTOM') && item.customExts.msgType==1" 
			:id="'s'+index">
			<view class="list" @click="NavInfoMsg('/pagesB/jobinfo/index?id='+item.customExts.orderId)">
				<view class="title">
					<view>{{item.customExts.title}}</view>
				</view>
				<view class="cont" v-if="item.customExts.workDesc">{{item.customExts.workDesc}}</view>
							
				<view class="tag">
					<view v-if="item.customExts.itemList[0].salaryUnit" class="t1">{{item.customExts.itemList[0].salaryUnit}}</view>
					<view v-if="item.customExts.settlementStr">{{item.customExts.settlementStr}}</view>
					<block v-if="item.customExts.welfares">
						<view v-for="(childitem,childindex) in item.customExts.welfares">{{childitem}}</view>
					</block>
				</view>
			  <view class="info">
			    <view class="left">
			      <view class="top">
			        <view class="name">{{item.customExts.nickName?item.customExts.nickName:'contactsName'}}</view>
						<block v-if="item.customExts.isEnterPrise == 0 && item.customExts.isRealName == 1">
							<image src="http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/user-real.svg" />
							<view class="authMe" v-if="">实名认证</view>
						</block>
						<block v-if="item.customExts.isEnterPrise == 1 && item.customExts.isRealName == 1">
							<image src="http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/comp-real.svg" />
							<view class="comp">企业认证</view>
						</block>
			      </view>
			    </view>
			    <view class="right">
			      <text>查看详情</text>
			    </view>
			  </view>
			</view>
		</view>
		<view class="master-block" 
			v-else-if="(item.type=='custom' || item.contentsType=='CUSTOM') && item.customExts.msgType==2" 
			:id="'s'+index">
			<view class="master-item" @click="NavInfoMsg('/pagesB/workInfo/RecruitmentInfo?id='+item.customExts.userId)">
				<view class="master-faceItem poser dis-row">
					<!--头像处理start-->
					<view class="faceItem-ico poser">
						<image :src="item.customExts.avatar?item.customExts.avatar:'http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/default-avatar.png'"></image>
						<label>{{item.customExts.staffTypeStr}}</label>
					</view>
					<!--头像处理over-->
					<!--顶部右侧标题文字开始-->
					<view class="faceText dis-clm">
						<!--置顶信息start-->
						<view class="faceText-t1 dis-row">
							<!-- <view class="zhidding">置顶</view> -->
							<view class="master-name">{{item.customExts.nickName}}</view>
							<block v-if="item.customExts.isRealName">
								<label><image src="http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/user-real.svg"></image></label>
								<text>实名认证</text>
							</block>
						</view>
						<!--置顶信息over-->
						<view class="master-userinfo dis-row">
							<text v-if="item.customExts.gender">
								<block v-if="item.customExts.gender==1">男</block>
								<block v-else-if="item.customExts.gender==2">女</block>
							</text>
							<text v-if="item.customExts.age">{{item.customExts.age}}岁</text>
							<text v-if="item.customExts.nationStr">{{item.customExts.nationStr}}</text>
						</view>
					</view>
					<!--顶部右侧标题文字结束-->
					<!--是否在线开始-->
					<!-- <view class="master-t3 dis-row" v-if="item.customExts.status">
						<view><label></label></view><text>今日找活中</text>
					</view> -->
					<!--是否在线结束-->
				</view>
				<!--标签列表开始-->
				<view class="bloc-small">
					<label v-if="item.customExts.workYear">{{item.customExts.workYear}}年工龄</label>
					<label v-if="item.customExts.workType1Str">{{item.customExts.workType1Str}}</label>
					<label v-if="item.customExts.masteryStr">{{item.customExts.masteryStr}}</label>
				</view>
				<view class="block-pre" style="color: #A1A1A1;font-size: 28rpx;">{{item.customExts.notice}}</view>
				<!--标签列表结束-->
				<!--底部开始哦-->
				<view class="master-zpList dis-clm poser">
					<view class="zpList-child dis-row">
						<label>期望工种</label><text>{{strHandle(item.customExts.skills)}}</text>
					</view>
					<view class="zpList-child dis-row">
						<label>期望地点</label><text>{{strHandle(item.customExts.hopeAddr)}}</text>
					</view>
					<view class="zpList-right dis-clm" v-if="item.customExts.salary">
						<view class="zplistrv-s1 dis-row"><label>{{item.customExts.salary}}</label>{{item.customExts.salaryUnitStr?item.customExts.salaryUnitStr:'元'}}</view>
						<view class="zpList-s2">期望薪资</view>
					</view>
				</view>
				<!--底部结束-->
			</view>
		</view>
		<view class="msgList" v-else :id="'s'+index">
			<view class="llist" v-if="item.from==toUser" :key="index" :id="'id-'+index">
				<view class="icon">
					<image mode="aspectFill" :src="user1.avatar"></image>
				</view>
				<view class="msg">
					<view class="msgName">{{user1.nick_name?user1.nick_name:'先生'}}</view>
					<text class="msgCon">{{item.msg?item.msg:item.sourceMsg}}</text>
				</view>
			</view>
			
			<view class="rlist" v-else :id="'id-'+index">
				<view class="msg">
					<view class="msgName">{{user2.nick_name?user2.nick_name:'先生'}}</view>
					<text class="msgCon">{{item.msg?item.msg:item.sourceMsg}}</text>
				</view>
				<view class="icon">
					<image mode="aspectFill" :src="user2.avatar"></image>
				</view>
			</view>
			
		</view>
		</block>
		<view style="height: 140rpx;"></view>
		</scroll-view>
		<view class="senMsg" :style="{'bottom': keyheight+'px'}">
			<view class="sendInput"><u--input
			placeholder="请输入内容"
			border="none"
			cursorSpacing='20'
			:adjustPosition="false"
			v-model="message"
			></u--input></view>
			<view class="sendBut"><u-button type="primary" @click="sendPrivateText()" text="发送"></u-button></view>
		</view>
		<!--熟练度-->
		<pop ref="mastery" direction="below" :is_close="true" :is_mask="true" :width="100">
			<view class="popOption">
				<view class="title">请对此人做出评价</view>
				<view class="option">
					<view
						v-for="(uv,ui) in levelList" 
						:key="ui" 
						:class="{'active':levelId === uv.id}" 
						@click="personChange(uv)">{{uv.name}}</view>
				</view>
				<view class="define">
					<view @click="personDefine()">确定</view>
				</view>
			</view>
		</pop>
	</view>
	
</template>
<script>
	import store from '@/common/store.js'
	import Index from '@/common/index-model.js'
	import pop from "@/components/ming-pop/ming-map.vue"
	let disp = require("../../utils/broadcast");
	let index=new Index()
	export default {
		data() {
			return {
				toUser:'',
				orderinfo:{},
				message:'',
				orderid:"",
				userid:"",
				user1:'',
				user2:'',
				historiMessages:[],
				scrollInto:'testc',//滚动到最后一个元素
				scrollTop:0,
				levelList:[],
				levelId:0,
				userFrom:{},
				loginHxName:uni.getStorageSync('hxuser'),
				meHxName:'',
				meUserId:'',
				toHxName:'',
				toUserId:'',
				scrollHeight:420,
				scrollclass:'scroll1',
				cursor:-1,
				keyheight:0
				
			}
		},
		components:{
			pop
		},
		onLoad(opt) {			
			let that=this;
			that.toUser=opt.user;			
			if(opt.orderid){
				that.orderid=opt.orderid;
				that.getOrderInfo();
			}
			if(opt.userid){
				that.userid=opt.userid;
				that.getCardInfo();
			}
			that.getHistoriMessages();
			that.getUserInfo();
			that.getUserFrom();
			disp.on("em.unreadspot", (res) => {
				that.historiMessages.push(res);
				that.$nextTick(() => {
					that.setScroll();
				})
			
			})
			
			//  监听键盘高度变化
			uni.onKeyboardHeightChange((obj)=>{
			    // 获取系统信息
				let _sysInfo = uni.getSystemInfoSync();
				let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight
				let _diff = obj.height - _heightDiff
				// 键盘高度
				let height = (_diff > 0 ? _diff : 0);
				this.keyheight=height;
				console.log(height);
			})
		},
		methods: {
			scrollTopSS(){
				if(this.cursor && this.cursor!='undefined'){
					this.getHistoriMessages();
				}
			},
			//获取人员构成
			getPersonList() {
				index.getPublicUserMember({},'/client/public/find/evaluate/people','get',res=>{
					if(res.data.code == 200 && res.data.success){
						this.levelList=res.data.result;
					}
				})
			},
			checkperson(){
				this.getPersonList();
				this.$refs.mastery.show();
			},
			personChange(item){
				this.levelId=item.id;
			},
			personDefine(){
				let url="/client/public/add/people"
				index.getPublicUserMember({targetId:this.user1.id,tindex:this.levelId},url,'POST',res=>{
					if(res.data.code==200){
						index.show_tips('评价成功！');
					}else{
						index.show_tips('评价失败，请稍后重试！');
					}
				})
				this.$refs.mastery.close();
			},
			getPhone(){
				index.getPublicUserMember({},"/client/individual/mobile/show?userId="+this.user1.id,'get',res=>{
					if(res.data.code==200){
						uni.showModal({
							title: '系统提示',
							content: res.data.result,
							showCancel: true,
							cancelText: '取消',
							success: function(res) {
							}
						});
					}
				})
			},
			getUserFrom(){
				let url="/client/message/check/fromto"
				index.getPublicUserMember({userId1:this.toUser,userId2:uni.getStorageSync('hxuser')},url,'get',res=>{
					if(res.data.code==200){
						this.userFrom=res.data.result;
					}
				})
			},
			callTel(){
				let url="/secret/call/secretNumber"
				index.getPublicUserMember({targetId:this.user1.id},url,'POST',res=>{
					if(res.data.code==200){
						uni.makePhoneCall({
							phoneNumber: res.data.result
						});
					}else if(res.data.code == 100017){
						index.show_tips('请完善您的个人信息')
						setTimeout(()=>{
							index.navigate_to('/pagesC/my/MyEditUserInfo');
						},2000)
					}
				})
			},
			getHistoriMessages(){
				let that=this;
				let options = {
					targetId: that.toUser,
					pageSize: 20,
					cursor:this.cursor,
					chatType: "singleChat",
					searchDirection: "up",
				};
				that.$WebIM.conn.getHistoryMessages(options).then((res) => {
					console.log(res);
					let mes=res.messages;
					if(this.cursor==-1){
						mes=mes.reverse();
						that.historiMessages=mes;
					}else{
						mes.forEach((item,index)=>{
							that.historiMessages.unshift(item);
						})
					}
					
					if(this.cursor==-1){
						that.$nextTick(() => {
							that.setScroll();					
						})
					}else{
						that.$nextTick(() => {
							that.setScroll('s'+mes.length);					
						})
					}
					this.cursor=res.cursor;
				}).catch((e) => {
				});
				
				let option = {
				  chatType: "singleChat", // 会话类型，设置为单聊。
				  type: "channel", // 消息类型。
				  to: that.toUser, // 接收消息对象的用户 ID。
				};
				let msg = that.$WebIM.message.create(option);
				that.$WebIM.conn.send(msg);
				
			},
			// 单聊发送文本消息
			sendPrivateText() {
				let that=this;
				if(!that.message){
					return false;
				}
				
			    let id = this.$WebIM.conn.getUniqueId();                 // 生成本地消息id
			    let msg = new that.$WebIM.message('txt', id);      // 创建文本消息
			    msg.set({
			        msg: that.message,                  // 消息内容
			        to: that.toUser,                          // 接收消息对象（用户id）
			        chatType: 'singleChat',                  // 设置为单聊
			        ext: {},                                  //扩展消息
			        success: function (id, serverMsgId) {
						let send={
							chatType:"singleChat",
							from:uni.getStorageSync('hxuser'),
							id:id,
							msg:that.message,
							onlineState:3,
							time:1678349247950,
							to:that.toUser,
							type:"txt",
						};
						that.message='';
						that.historiMessages.push(send);
						that.$nextTick(() => {
							that.setScroll();
						})
			        }, 
			        fail: function(e){
						uni.showToast({
							title: '发送失败',
							duration: 2000
						});
			        }
			    });
			    that.$WebIM.conn.send(msg.body);
			},
			sendCustomMsg(data) {
				let that=this;
				// 自定义事件。
				let customEvent = "customEvent";
				// 通过键值对设置自定义消息内容。
				let customExts = data;
				let option = {
					// 消息类型。
					type: "custom",
					// 消息接收方：单聊为对方用户 ID，群聊和聊天室分别为群组 ID 和聊天室 ID。
					to: that.toUser,
					// 会话类型：单聊、群聊和聊天室分别为 `singleChat`、`groupChat` 和 `chatRoom`。
					chatType: "singleChat",
					customEvent,
					customExts,
					// 消息扩展字段，不能设置为空，即设置为 "ext:null" 这种形式会出错。
					ext: {},
				};
				// 创建一条自定义消息。
				let msg = that.$WebIM.message.create(option);
				// 调用 `send` 方法发送该自定义消息。
				that.$WebIM.conn.send(msg).then((res) => {
					let send={
						chatType: "singleChat",
						customEvent: "customEvent",
						customExts: data,
						from: uni.getStorageSync('hxuser'),
						id: res.serverMsgId,
						onlineState: 3,
						time: 1680071754430,
						to: that.toUser,
						type: "custom"
					};
					that.historiMessages.push(send);
					console.log(that.historiMessages);
					that.orderid='';
					that.userid='';
					
				}).catch((e) => {
					// 消息发送失败回调。
					//console.log("Fail");
				});
			},
			addCard(){
				let url="/client/collectCard/add"
				index.getPublicUserMember({tartgetId:this.user1.id},url,'post',res=>{
					if(res.data.code==200){
						uni.showToast({
							title: '加入成功',
							duration: 2000
						});
					}
				})
			},
			getUserInfo(){
				let url="/client/public/query/user"
				index.getPublicUserMember([this.toUser,uni.getStorageSync('hxuser')],url,'post',res=>{
					if(res.data.code==200){
						let userlist=res.data.result;
						const user1 = userlist.filter(
						    (item) => item.hx_name == this.toUser
						);
						const user2 = userlist.filter(
						    (item) => item.hx_name == uni.getStorageSync('hxuser')
						);
						let userc1=user1[0];
						userc1.avatar=userc1.avatar?userc1.avatar:'http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/default-avatar.png';
						let userc2=user2[0];
						userc2.avatar=userc2.avatar?userc2.avatar:'http://xgr.oss-cn-hangzhou.aliyuncs.com/icon/images/default-avatar.png';
						this.user1=userc1;
						this.user2=userc2;
					}
				})
			},
			//获取详情
			getOrderInfo() {
				let url="client/job/find/details/"+this.orderid
				index.getPublicUserMember({},url,'get',res=>{
					if(res.data.code == 200 && res.data.success){
						let data=res.data.result;
						let jobReq=index.strTrim(data.jobReq,',');
						data.jobReqList=jobReq?jobReq.split(','):'';
						let welfare=index.strTrim(data.welfare,',');
						data.welfareList=welfare?welfare.split(','):'';
						data.msgType=1;
						this.$nextTick(() => {
							this.sendCustomMsg(data);
						})
					}
				})
			},
			//获取详情
			getCardInfo() {
				index.getPublicUserMember('','client/card/detail/'+this.userid,'get',res=>{
					if(res.data.code == 200 && res.data.success){
						let data=res.data.result;
						data.msgType=2;
						this.sendCustomMsg(data);
					}
				})
			},
			setScroll(id){
			    let len = this.historiMessages.length;
				if(!id){
					this.scrollInto = 's'+(len-1);
				}else{
					this.scrollInto = id;
				}
			},
			NavInfoMsg(url) {
				index.navigate_to(url)
			},
			strHandle(str,char=','){
				str=index.strTrim(str,char);
				return index.strRep(str,char,'、');
			}
		}
	}
</script>
<style>
	@import url('./index.css');
</style>
<style lang="scss" scoped>
@import url("@/static/css/publics.css");
::v-deep {
  .u-navbar--fixed {	
	  background: #fff;
	  font-size: 36rpx;
    & > view {
      background: transparent !important;
	  
    }
    .leftText {
      color: #000;
	  font-size: 36rpx;
	  font-weight: bold;
    }
	.search{ border: 1px solid #E4F0FF; margin-right: 180rpx; display: flex; justify-content: center; color: #3D3D3D; font-size: 24rpx; border-radius: 48rpx; width: 160rpx; height: 48rpx; line-height: 48rpx; text-align: center;}
	.search image{width: 30rpx; height: 30rpx; margin-right: 10rpx; margin-top: 8rpx;}
  }
}



.list {
      padding: 20rpx 20rpx 0;
	  margin-bottom: 60rpx;
      border-bottom: 10rpx solid #f3f3f3;
	  background: #fff;
      .title {
        display: flex;
        align-items: center;
		flex-wrap: wrap;
		vertical-align: top;
		align-items: flex-start;
        text {
          background: #ff5964;
          color: #fff;
          font-size: 20rpx;
          border-radius: 8rpx;
		  margin-right: 20rpx;
		  width: 64rpx;
		  margin-top: 6rpx;
			height: 38rpx;
			line-height: 38rpx;
			text-align: center;
			vertical-align: top;
        }
        view {
          font-size: 36rpx;
          font-weight: bold;
          width: calc(100% - 90rpx);
		  line-height: 42rpx;
        }
      }
      .cont {
        margin: 20rpx 0;
        font-size: 26rpx;
        color: #424242;
      }
      .tag {
        display: flex;
		flex-wrap: wrap;
        view {
          background: #f7f7f7;
          border-radius: 8rpx;
          font-size: 28rpx;
          padding: 10rpx;
          margin-right: 10rpx;
          color: #424242;
		  margin-bottom: 10rpx;
        }
        .t1 {
          color: #ff5964;
        }
      }
      .info {
        padding-top: 20rpx;
        padding-bottom: 30rpx;
        margin-top: 20rpx;
        align-items: baseline;
        border-top: 0.5px solid #f0f0f0;
        display: flex;
        justify-content: space-between;
        .left {
          .top {
            display: flex;
            align-items: center;
            .name {
              color: #0f0f0f;
              font-weight: bold;
            }
            image {
              width: 28rpx;
              height: 28rpx;
			  margin-left: 14rpx;
			  margin-right: 10rpx;
            }
            .authMe {
              color: #a1a1a1;
              font-size: 24rpx;
            }
			.comp {
			  color: #d9a14e;
			  font-size: 24rpx;
			}
          }
          .addr {
            display: flex;
            color: #a1a1a1;
            font-size: 24rpx;
            margin-top: 10rpx;
            ::v-deep {
              .u-icon {
                margin-right: 14rpx;
              }
            }
          }
        }
        .right {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
		  text{ color: #0F0F0F; font-size: 28rpx;}
        }
      }
    }
</style>